package common

import (
	"encoding/json"
	"fmt"
	"math/rand"
	"net"
	"strconv"
	"strings"
)

//打印值和类型
func TypeAndValue(in interface{}) {
	fmt.Println("value:", in)
	fmt.Println(fmt.Sprintf("type: %T", in))
}

//job 反序列化
func UnpackJob(bytes []byte) (rs *Job, err error) {
	job := &Job{}
	if err = json.Unmarshal(bytes, job); err != nil {
		return
	}
	return job, nil
}

//从etcd key中提取任务名
func ExtractJobName(jobKey, dir string) string {
	return strings.Trim(jobKey, dir)
}

//字符串转int
func StrToInt(s string, i int64) (rs int64) {
	if s == "" {
		return i
	}
	rsInt, err := strconv.Atoi(s)
	if err != nil {
		return i
	}
	return int64(rsInt)
}

//获取local ip
func GetLocalIp() (ip4 string, err error) {
	addrs, err := net.InterfaceAddrs()
	if err != nil {
		return
	}

	for _, addr := range addrs {
		if ipNet, ok := addr.(*net.IPNet); ok && !ipNet.IP.IsLoopback() {
			if ipNet.IP.To4() != nil {
				ip4 = ipNet.IP.String()
				return
			}
		}
	}
	err = ERR_REGISTER_INFO
	return
}

func GetRand() string {
	return strconv.Itoa(rand.Intn(9999))
}
